import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Scanner;
import java.net.*;
public class Client5_3 {
    public static void main(String[] args) {
        //客户端让用户输入中缀表达式，然后把中缀表达式调用MyBC.java的功能转化为后缀表达式，把后缀表达式通过网络发送给服务器
        Scanner scanner = new Scanner(System.in);
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try{
            mysocket = new Socket("127.0.0.1",2010);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            System.out.println("请输入要计算的题目：");
            String formula = scanner.nextLine();
            String regex = ".*[^0-9|+|\\-|*|÷|(|)|\\s|/].*";
            if(formula.matches(regex)){
                System.out.println("输入了非法字符");
                System.exit(1);
            }
            String output = "";
            MyBC myBC = new MyBC();
            try{
                output = myBC.getEquation(formula);//中缀转后缀
            }catch (ExprFormatException e){
                System.out.println(e.getMessage());
                System.exit(1);
            }
            KeyGenerator kg = KeyGenerator.getInstance("AES");
            kg.init(128);
            SecretKey k = kg.generateKey();//生成密钥
            Cipher cp = Cipher.getInstance("AES");
            cp.init(Cipher.ENCRYPT_MODE,k);
            byte ptext[] = output.getBytes("UTF8");
            byte ctext[] = cp.doFinal(ptext);
            String out1 = B_H.parseByte2HexStr(ctext);//后缀表达式的加密
            //调用MyBC得到后缀表达式
            //System.out.println("后缀表达式加密结果为："+out1);
            out.writeUTF(out1);//将后缀表达式加密后传给Server
            byte kb[] = k.getEncoded();
            String Key = B_H.parseByte2HexStr(kb);
            //System.out.println("密钥为："+Key);
            out.writeUTF(Key);//将密钥传给服务器
            String s = in.readUTF();
            System.out.println("客户收到服务器的回答："+s);
        }catch (Exception e){
            System.out.println("服务器已断开"+e);
        }
    }
}

